<template>
  <div v-if="enterpriseLoginVisible" class="login-form-container">
    <a-typography-title class="login-welcome">
      <div v-html="loginTitle" />
    </a-typography-title>
    <a-form
      :model="loginState"
      name="login"
      layout="vertical"
      :rules="loginRules"
      hide-required-mark
      @finish="login"
      class="login-form"
    >
      <a-form-item
        label="企业代码"
        name="no"
        :class="loginState.no ? 'login-form-item-fill' : ''"
      >
        <a-input
          v-model:value="loginState.no"
          size="large"
          allow-clear
          :maxlength="30"
        />
      </a-form-item>
      <a-form-item
        label="手机号"
        name="mobile"
        :class="loginState.mobile ? 'login-form-item-fill' : ''"
      >
        <a-input
          v-model:value="loginState.mobile"
          size="large"
          allow-clear
          :maxlength="11"
        />
      </a-form-item>
      <a-form-item
        label="密码"
        name="password"
        :class="loginState.password ? 'login-form-item-fill' : ''"
      >
        <!--设置属性 autocomplete="new-password" 解决浏览器自动填充问题-->
        <a-input
          v-model:value="loginState.password"
          type="password"
          size="large"
          allow-clear
          :maxlength="16"
          autocomplete="new-password"
        >
          <template #suffix>
            <!--<eye-outlined />-->
            <!--<eye-invisible-outlined />-->
            <a-button
              type="link"
              @click.prevent.stop="resetPassVisible = true"
              style="padding: 0"
              >忘记密码?</a-button
            >
          </template>
        </a-input>
      </a-form-item>
      <br />
      <a-form-item>
        <a-button
          type="primary"
          size="large"
          block
          :loading="loading"
          html-type="submit"
          >登录{{ loading ? "中..." : "" }}</a-button
        >
      </a-form-item>
    </a-form>
    <reset-password-dialog v-model:visible="resetPassVisible" />
  </div>
  <multi-enterprise-login
    v-else
    :login-state="loginState"
    :enterprises="enterprises"
    @close="returnLogin"
  />
</template>

<script lang="ts" setup>
import { reactive, ref, useAttrs } from "vue";
import { useStore } from "@/store/index";
import ResetPasswordDialog from "@/components/dialog/reset-password-dialog.vue";
import {
  validatePassword,
  validatePhone,
} from "@/utils/yuxin-main/formValidation";
import type { Rule } from "ant-design-vue/es/form";
import MultiEnterpriseLogin from "./multi-enterprise-login.vue";
import { message } from "ant-design-vue";
import { isLockinEnv } from "@utils/common/index";
import {
  getEnterpriseList,
  getMenusList,
  getUserToken,
} from "@/api/yuxin-main/user";

const { hostname } = location;

const store = useStore();
const attrs = useAttrs();
const { shouldShowIcon } = attrs;
const loginTitle = ref<string>("欢迎登录<br/>寓信智慧公寓管理系统");

const titleMap: any = {
  // 商务演示域名，不带寓信元素
  "prod.yxpms.com": "欢迎登录<br/>智慧公寓管理系统",
  // 城盈住房环境
  "saas.cyzf.cn": "欢迎登录<br/>住房服务管理系统",
  // 城住数科环境
  "czpms.cyzf.cn": "欢迎登录城住数科<br/>住房服务管理系统",
};

if (titleMap.hasOwnProperty(hostname)) {
  loginTitle.value = titleMap[hostname];
} else if (isLockinEnv()) {
  loginTitle.value = shouldShowIcon
    ? "欢迎登录明智云<br/>智慧社区 选择明智"
    : "欢迎登录";
}

const loginState = reactive<any>({
  no: null,
  mobile: null,
  password: null,
  grant_type: "password",
});

const loginRules: Record<string, Rule[]> = {
  no: [{ required: true }],
  mobile: [{ required: true, validator: validatePhone }],
  password: [{ required: true, validator: validatePassword }],
};

const loading = ref<boolean>(false);
const enterprises = ref<any[]>([]);
const resetPassVisible = ref<boolean>(false);
const enterpriseLoginVisible = ref<boolean>(true);
const enterpriseLoginPromise = ref<any>(null);

/**
 * 登录请求
 */
const login = async () => {
  loading.value = true;
  console.log("login", '4545454');
  await loginStep().catch((e) => {
    console.log('===>e',e);
  });
  loading.value = false;
};

const loginStep = async () => {
  const { token, enterprise } = await getToken();
  const menu = await getMenu();
  console.log('===>66666',);
  store.userLogin({ loginState, token, enterprise, menu });
};

const getToken = async () => {
  const { data } = await getUserToken(loginState);
  const { token, shopInfo: enterprise } = data || {};
  if (!token.value) {
    message.error("获取 token 失败，请联系管理员");
    return Promise.reject();
  }
  store.setAccessToken(token.value);
  store.setEnterprise(enterprise);
  return { token: token.value, enterprise };
};

const getMenu = async () => {
  const { data } = await getMenusList();
  if (!Array.isArray(data)) {
    message.error("菜单数据有误，请联系管理员");
    return Promise.reject();
  }
  if (!data.length) {
    message.error("当前账号无权限访问系统");
    return Promise.reject();
  }
  return data;
};

const selectEnterprises = (enterpriseData:any) => {
  return new Promise((resolve, reject) => {
    enterprises.value = enterpriseData;
    enterpriseLoginVisible.value = false;
    enterpriseLoginPromise.value = { resolve, reject };
  });
};

/**
 *返回从新登录
 */
const returnLogin = (enterprise:any) => {
  const { resolve, reject } = enterpriseLoginPromise.value || {};
  if (enterprise) resolve?.(enterprise);
  else {
    enterpriseLoginVisible.value = true;
    reject?.();
  }
};
</script>
<style lang="less" scoped>
.ant-carousel :deep(.slick-slide) {
  text-align: center;
  overflow: hidden;
}

.login-form-container {
  padding: 15% 40px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;

  animation: fadeInAnimation ease 1.5s;
  animation-iteration-count: 1; /*设置动画播放次数*/
  animation-fill-mode: forwards;
  @keyframes fadeInAnimation {
    0% {
      opacity: 0; /*设置不透明度*/
    }
    100% {
      opacity: 1;
    }
  }

  .login-welcome {
    color: @primary-color;
    white-space: pre-line;
  }

  .login-form {
    .ant-form-item {
      :deep(.ant-input) {
        height: 32px;
      }

      .ant-input,
      .ant-input-affix-wrapper {
        padding: 6px 0;
        box-shadow: none !important;
        border-width: 0 0 2px 0 !important;
      }

      &:focus-within,
      &.login-form-item-fill {
        :deep(.ant-form-item-label) {
          top: 10px;

          label {
            color: initial;
          }
        }
      }
    }
  }

  :deep(.login-form) {
    .ant-form-item-label {
      z-index: 99;
      top: 40px;
      position: relative;
      pointer-events: none;
      transition: top 300ms;

      label {
        color: @disabled-color;
        transition: color 300ms;
      }
    }
  }
}
</style>
